<script setup>
import { ref, defineEmits } from 'vue'
import { getCategoryListApi } from '@/apis/category'
import { Delete, Edit, Sell, SoldOut } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import {
  getGoodsListApi,
  updateGoodsSellStatusApi,
  deleteGoodsApi
} from '@/apis/goods'
const emit = defineEmits(['title'])
emit('title', '商品管理')
const router = useRouter()

// 搜索表单
const params = ref({
  pageNo: 1,
  pageSize: 10,
  // sortBy: 'selling_price',
  goodsName: '',
  categoryId: null,
  goodsSellStatus: null,
  beginTime: null,
  endTime: null
})

const total = ref(0)
const categoryList = ref([])

// 获取分类列表
const getCategoryList = async () => {
  const res = await getCategoryListApi()
  categoryList.value = res.data.data
}
getCategoryList()

// 改变分类选择
const changeCategory = (e) => {
  if (e && e.length > 0) {
    params.value.categoryId = e[e.length - 1]
    console.log(params.value)
  }
}
// 翻页
const currentChange = (e) => {
  params.value.pageNo = e
  getGoodsList()
}
// 切换页大小
const sizeChange = (e) => {
  params.value.pageSize = e
  params.value.pageNo = 1
  getGoodsList()
}

// 搜索
const onSearch = () => {
  params.value.pageNo = 1
  getGoodsList()
}

// 重置搜索表单
const onReset = () => {
  params.value.goodsName = ''
  params.value.categoryId = null
  params.value.goodsSellStatus = null

  getGoodsList()
}

const tableData = ref([])
const columns = [
  {
    prop: '',
    type: 'selection',
    fixed: 'left'
  },
  {
    prop: 'id',
    type: 'text',
    label: '商品编号',
    fixed: 'left'
  },
  {
    label: '图片',
    prop: 'goodsCoverImg',
    type: 'img',
    width: 150,
    config: {
      width: '6.5rem',
      height: '5.8rem'
    }
  },
  {
    prop: 'goodsName',
    label: '名称',
    type: 'text',
    width: 200
  },
  {
    prop: 'goodsIntro',
    label: '简介',
    type: 'text',
    width: 200
  },
  {
    prop: 'goodsCategoryName',
    label: '分类名',
    type: 'text'
  },

  {
    prop: 'originalPrice',
    label: '价格',
    type: 'price',
    width: 100
  },
  {
    prop: 'sellingPrice',
    label: '售价',
    type: 'price',
    width: 100
  },

  {
    prop: 'stockNum',
    label: '库存',
    type: 'text'
  },
  {
    prop: 'tag',
    label: '标签',
    type: 'tags',
    width: 150
  },
  {
    prop: 'goodsSellStatus',
    label: '状态',
    type: 'enum',
    width: 100,
    enum: [
      {
        value: 0,
        label: '在售',
        color: 'green'
      },
      {
        value: 1,
        label: '已下架',
        color: 'red'
      }
    ]
  },
  {
    prop: 'createTime',
    label: '创建时间',
    type: 'date',
    width: 150
  },
  {
    prop: '',
    type: 'operate',
    label: '操作',
    width: 220,
    fixed: 'right'
  }
]

const getGoodsList = async () => {
  const res = await getGoodsListApi(params.value)
  tableData.value = res.data.data.list
  total.value = res.data.data.total
}

getGoodsList()

const ids = ref([])
// 多选
const handleSelectionChange = (e) => {
  ids.value = e
  console.log(ids.value)
}

// 跳转到新增页面
const open = (id) => {
  if (id) {
    router.push(`/overview/add-goods?id=${id}`)
  } else {
    router.push('/overview/add-goods')
  }
}

// 删除
const onDelete = async (id) => {
  if (id) {
    ids.value = []
    ids.value.push(id)
  }
  if (ids.value.length === 0) {
    ElMessage({
      message: '请选择要删除的数据',
      type: 'warning'
    })
    return
  }

  await ElMessageBox.confirm('确定删除吗？', '温馨提示', {
    confirmButtonText: '删除',
    cancelButtonText: '取消',
    type: 'warning'
  })

  await deleteGoodsApi(ids.value)
  ElMessage({
    message: '删除成功',
    type: 'success'
  })
  getGoodsList()
}

// 修改商品状态
const onUpdateGoodsSellStatus = async (row) => {
  await updateGoodsSellStatusApi(row.id)
  ElMessage({
    message: '修改成功',
    type: 'success'
  })
  getGoodsList()
}
</script>

<template>
  <div class="page">
    <TabComponent
      :tableData="tableData"
      :columns="columns"
      @selectionChange="handleSelectionChange"
      :height="455"
    >
      <template #header>
        <div class="search-box">
          <el-form :inline="true" :model="params" class="search-form">
            <el-form-item label="商品名字">
              <el-input
                style="width: 12rem"
                v-model="params.goodsName"
                placeholder="请输入商品名"
                clearable
              />
            </el-form-item>

            <el-form-item label="商品分类">
              <el-cascader
                v-model="params.categoryId"
                :options="categoryList"
                :props="{ value: 'id', label: 'categoryName' }"
                @change="changeCategory"
                :clearable="true"
                @clear="params.categoryId = null"
              />
            </el-form-item>

            <el-form-item label="商品状态">
              <el-select
                v-model="params.goodsSellStatus"
                placeholder="请选择商品状态"
                style="width: 8rem"
                clearable
              >
                <el-option label="在售" :value="0" />
                <el-option label="已下架" :value="1" />
              </el-select>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="onSearch">搜索</el-button>
              <el-button type="default" @click="onReset">重置</el-button>
            </el-form-item>
          </el-form>
          <div class="operate-box">
            <el-button type="primary" @click="open(null)">新增</el-button>
            <el-button type="danger" @click="onDelete(null)">删除</el-button>
          </div>
        </div>
      </template>

      <template #operate="{ row }">
        <el-button
          :type="row.goodsSellStatus === 0 ? 'warning' : 'info'"
          link
          :icon="row.goodsSellStatus === 0 ? Sell : SoldOut"
          @click="onUpdateGoodsSellStatus(row)"
          >{{ row.goodsSellStatus === 0 ? '下架' : '起售' }}</el-button
        >
        <el-button type="primary" link :icon="Edit" @click="open(row.id)"
          >编辑</el-button
        >
        <el-button type="danger" link :icon="Delete" @click="onDelete(row.id)"
          >删除</el-button
        >
      </template>

      <template #pagination>
        <el-pagination
          v-show="total > 0"
          background
          layout="sizes,prev, pager, next,total"
          :total="total"
          :page-sizes="[2, 10, 15, 20]"
          v-model:page-size="params.pageSize"
          v-model:current-page="params.pageNo"
          @current-change="currentChange"
          @size-change="sizeChange"
        />
      </template>
    </TabComponent>
  </div>
</template>

<style lang="scss" scoped>
.page {
  width: 100%;

  .page-box {
    display: flex;
    justify-content: end;
  }

  .editor {
    width: 100%;

    :deep(.ql-editor) {
      min-height: 200px;
    }
  }
}
</style>
